package com.bby.disk.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.bby.common.exception.BBYException;
import com.bby.common.utils.R;
import com.bby.common.aop.ParseToken;
import com.bby.disk.bean.req.ThumbnailReq;
import com.bby.disk.exception.BBYExceptionHandler;
import com.bby.disk.manager.download.DirectLinkResult;
import com.bby.disk.service.IDownloadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * 网盘-下载
 */
@RestController
@RequestMapping("download")
public class DownloadController {
    IDownloadService downloadService;
    Logger logger = LoggerFactory.getLogger(this.getClass());

    public DownloadController(IDownloadService downloadService) {
        this.downloadService = downloadService;
    }

    /**
     * 下载
     *
     * @param fileId   要下载的文件id
     * @param directId 直链
     */
    @ParseToken
    @RequestMapping("direct/{fileId}")
    public void download(String userId, @PathVariable String fileId, String directId) throws Exception {
        logger.debug("下载：userId={},fileId={}", userId, fileId);
        if (ObjectUtil.isEmpty(fileId)) {
            throw BBYExceptionHandler.INPUT_ERROR_EX;
        }
        downloadService.download(fileId, directId);
    }

    /**
     * 在线视频
     *
     * @param fileId   视频文件id
     * @param directId 直链
     */
    @GetMapping("video/{fileId}")
    public void video(@PathVariable String fileId, String directId) throws Exception {
        logger.debug("video id={},directId={}", fileId, directId);
        downloadService.video(fileId, directId);
    }

    /**
     * 查看缩略图，即可看图也可看视频
     *
     * @param fileId 图片文件id
     * @param req    参数
     */
    @GetMapping("img/{fileId}")
    public void imgView(@PathVariable String fileId, ThumbnailReq req) throws Exception {
        req.setFileId(fileId);
        downloadService.imgView(req);
    }

    /**
     * 查看视频缩略图
     *
     * @param fileId   视频文件id
     * @param directId 直链id
     */
    @Deprecated
    @GetMapping("videoImg/{fileId}")
    public void viewVideoImg(@PathVariable String fileId, String directId) throws Exception {
        downloadService.viewVideoImg(fileId, directId);
    }

    /**
     * 获取头像
     *
     * @param avatar 用户id
     */
    @ParseToken
    @GetMapping("avatar/{avatar}")
    public void getAvatar(String userId, @PathVariable String avatar, HttpServletResponse response) {
        if (ObjectUtil.isEmpty(avatar)) {
            avatar = userId;
        }
        if (ObjectUtil.isEmpty(avatar)) {
            response.setStatus(HttpStatus.HTTP_NOT_FOUND);
        } else {
            downloadService.getAvatar(avatar, response);
        }
    }

    @ParseToken
    @GetMapping("text/{fileId}")
    public R textView(String userId, @PathVariable String fileId, String directId, HttpServletResponse response) throws Exception {
//        response.getOutputStream().print( "没错就是我");
        if (directId == null) {
            return R.error("错误信息");
        }
        File file = new File("C:\\Users\\24686\\Desktop\\test.txt");
        return R.ok().setData(FileUtil.readUtf8String(file));
    }

    /**
     * 创建视频缩略图，返回: Map《fileId,DirectLink》
     *
     * @param fileId 可为多个
     * @return 返回: Map《fileId,DirectLink》
     */
    @Deprecated
    @ParseToken
    @GetMapping("createVideoImg")
    @ResponseBody
    public R createVideoImg(String userId, @RequestParam("fileId") List<String> fileId) throws BBYException {
        logger.debug("createVideoImg：userId={},id={}", userId, fileId);
        if (ObjectUtil.isEmpty(fileId)) {
            return R.error("提供的参数不符合规范");
        }
        return R.ok(downloadService.createVideoImg(userId, fileId));
    }

    /**
     * 创建直链
     *
     * @param fileId path/fileId值id:使用文件id; ids:多个文件，返回map，只能用id
     */
    @ParseToken
    @GetMapping("create")
    @ResponseBody
    public R createDirectLink(String userId, @RequestParam("fileId") List<String> fileId) throws Exception {
        logger.debug("创建直链：userId={},targets={}", userId, fileId);
        if (ObjectUtil.isEmpty(fileId)) {
            return R.error("提供的参数不符合规范");
        }
        if (fileId.size() == 1) {
            return R.ok().setData(downloadService.createDirectLink(userId, fileId.get(0)));
        }
        return R.ok(downloadService.createDirectLinks(userId, fileId));
    }

    /**
     * 批量创建直链，用于生成缩略图
     *
     * @param list 图片id列表
     * @return
     * @throws Exception
     */
    @ParseToken
    @PostMapping("create/ids")
    @ResponseBody
    public R getDirectLink(String userId, @RequestParam List<String> list) throws Exception {
        logger.debug("创建直链：userId={},fileList={}", userId, list);
        if (ObjectUtil.isEmpty(list)) {
            throw BBYExceptionHandler.INPUT_ERROR_EX;
        }
        Map<String, DirectLinkResult> resultMap = downloadService.createDirectLinks(userId, list);
        return R.ok(list.size() == 1 ? resultMap.values().toArray()[0] : resultMap);
    }

}
